package com.yanghui.lingyue.functions.game

import com.icedata.sika.bridge.SikaEvent
import com.icedata.sika.bridge.SikaGroupEvent
import com.icedata.sika.bridge.SikaUserEvent
import com.icedata.sika.core.CommandProcessor
import com.icedata.sika.core.ParseProcessor
import com.icedata.sika.core.Sika
import com.yanghui.lingyue.bot.Bot
import com.yanghui.lingyue.data.Command
import com.yanghui.lingyue.functions.AbstractFunction
import com.yanghui.lingyue.functions.apiBase.SendMotto
import com.yanghui.lingyue.utils.functionUtils.FunctionUtils
import java.util.*

@Deprecated("Sika内部的任务挂载功能存在bug，该API暂时停用", level = DeprecationLevel.ERROR)
object GameEntry : AbstractFunction() {
    override val name: String = "Game"
    private val gameCommandProcessorList: LinkedHashMap<String, CommandProcessor> = LinkedHashMap()
    private val gameParseProcessorList: LinkedHashMap<String, ParseProcessor> = LinkedHashMap()

    override suspend fun parse(event: SikaEvent, sika: Sika): LinkedList<Command> {
        val command = LinkedList<Command>()
        if (event is SikaUserEvent) return command
        event as SikaGroupEvent
        if (!FunctionUtils.atBot(event)) return command
        if (!FunctionUtils.checkValid(event)) return command
        if (event.sendGroup.id !in enableGroup) return command

        val param = FunctionUtils.extractKeyword(event, "开始游戏")
        param?.let {
            command.add(Command(event, name, it))
        }
        return command
    }

    override suspend fun execute(command: Command, sika: Sika): CommandProcessor.Result {
        if (command.param == "测试") {
            command.sendGroup?.sendMessage("游戏开始")
        }
        return CommandProcessor.Result.ADOPT
    }

    private fun startGame(function: GameFunction, startGroup: Long) {
        CommandProcessor(
            function = { command, sika ->
                function.execute(command as Command, sika)
            },
            filter = {
                function.filter(it as Command)
            }
        ).let {
            gameCommandProcessorList[function.name + startGroup] = it
            Bot.sikaCore.mountCommandProcessor(it)
        }
        ParseProcessor { event, sika ->
            function.parse(event, sika)
        }.let {
            gameParseProcessorList[function.name + startGroup] = it
            Bot.sikaCore.mountParseProcessor(it)
        }
    }

    private fun stopGame(function: GameFunction, endGroup: Long) {
        gameCommandProcessorList[function.name + endGroup]?.let {
            Bot.sikaCore.unmountCommandProcessor(it)
            gameCommandProcessorList.remove(function.name + endGroup)
        }
        gameParseProcessorList[function.name + endGroup]?.let {
            Bot.sikaCore.unmountParseProcessor(it)
            gameParseProcessorList.remove(function.name + endGroup)
        }
    }
}